package cn.edu.xaut.Dao;

import cn.edu.xaut.bean.Goods;
import cn.edu.xaut.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GoodsDao {
    public boolean insert(Goods goods)throws SQLException,ClassNotFoundException{
        //使用Dao来插入数据
        Connection conn= JDBCUtils.getConnection();

        String sql="insert into goods(goodsname,goodsprice) values(?,?)";
        PreparedStatement ps=conn.prepareStatement(sql);

        //设置参数,占位符
        ps.setString(1,goods.getGoodsname());
        ps.setFloat(2,goods.getGoodsprice());

        //执行SQL语句
        int update=ps.executeUpdate();

        //关闭数据库连接
        JDBCUtils.release(ps,conn);

        if (update>0)
            return true;
        else
            return false;
    }

    public List<Goods> findAll()throws SQLException,ClassNotFoundException{
        List<Goods> goodslist=new ArrayList<Goods>();

        //使用Dao来查询数据
        Connection conn=JDBCUtils.getConnection();
        String sql="select * from goods";
        PreparedStatement ps=conn.prepareStatement(sql);
        java.sql.ResultSet rs=ps.executeQuery();

        while(rs.next()){
            Goods goods=new Goods();
            goods.setId(rs.getString("id"));
            goods.setGoodsname(rs.getString("goodsname"));
            goods.setGoodsprice(rs.getFloat("goodsprice"));
            goodslist.add(goods);
        }
        JDBCUtils.release(rs,ps,conn);
        return goodslist;
    }

    public Goods findeById(String id)throws SQLException,ClassNotFoundException{
        //使用Dao来查询数据
        Connection conn=JDBCUtils.getConnection();
        String sql="select * from goods where id=?";
        PreparedStatement ps=conn.prepareStatement(sql);
        ps.setString(1,id);
        java.sql.ResultSet rs=ps.executeQuery();

        Goods goods=new Goods();
        while(rs.next()){
            goods.setId(rs.getString("id"));
            goods.setGoodsname(rs.getString("goodsname"));
            goods.setGoodsprice(rs.getFloat("goodsprice"));
        }
        JDBCUtils.release(rs,ps,conn);
        return goods;
    }

}
